/*
 * @author: huangww
 * @Date: 2021-03-01 11:25:47
 * @LastEditTime: 2021-03-01 15:32:47
 */
var fs = require("fs");
var path = require("path");
var tinify = require("tinify");
var crypto = require('crypto');
var process_file_ext = ["png", "jpg"];

var localPath = 'preVersionPackage/md5.json';
/**
 * 资源读取相对路径
 */
var readPath = "../../fishingMerge/resource/";
var readJson = {};

load();

function readDir(dir, obj) {
    var stat = fs.statSync(dir);
    if (!stat.isDirectory()) {
        return;
    }
    var subpaths = fs.readdirSync(dir), subpath, size, md5, relative;
    for (var i = 0; i < subpaths.length; ++i) {
        if (subpaths[i][0] === '.') {
            continue;
        }
        subpath = path.join(dir, subpaths[i]);
        stat = fs.statSync(subpath);
        if (stat.isDirectory()) {
            readDir(subpath, obj);
        }
        else if (stat.isFile()) {
            //类型过滤
            var ext_name = path.extname(subpath);
            ext_name = ext_name.substr(1);
            var is_process_file = false;
            for (var k = 0; k < process_file_ext.length; k++) {
                if (process_file_ext[k] === ext_name) {
                    is_process_file = true;
                    break;
                }
            }
            if (!is_process_file) {
                continue;
            }

            // Size in Bytes
            size = stat['size'];
            md5 = crypto.createHash('md5').update(fs.readFileSync(subpath)).digest('hex');

            relative = path.relative(readPath, subpath);
            relative = relative.replace(/\\/g, '/');
            relative = encodeURI(relative);

            obj[relative] = {
                'size': size,
                'md5': md5
            };
        }
    }
}

function load() {
    readJson = {};
    readDir(readPath, readJson);
    fs.writeFile(localPath, JSON.stringify(readJson), (err) => {
        if (err) throw err;
        console.log('complete');
    });
}
